package com.diors.game.engine.network;

import com.diors.commons.log.DiorsLogger;
import com.diors.commons.network.DiorsBuffer;
import com.diors.commons.network.DiorsConnection;
import com.diors.commons.network.ReceivablePacket;
import com.diors.commons.network.module.ModuleManager;
import com.diors.commons.network.module.Resolve;
import com.diors.commons.network.module.model.MethodModel;
import com.diors.game.engine.thread.ThreadPoolManager;

/**
 * 游戏连接包
 * @author darren.ouyang
 * @date 2013-9-10
 */
public class GameClientPacket extends ReceivablePacket
{

	static DiorsLogger log = DiorsLogger.getLogger(GameClientPacket.class);
	
	MethodModel methodModel;
	
	private Object[] objs;
	
	public GameClientPacket(DiorsConnection conn, DiorsBuffer dbuffer) 
	{
		super(conn, dbuffer);
	}

	@Override
	public boolean processData() 
	{
		int key = buffer.readShort();
		int opcode = buffer.readShort();
		
		MethodModel model = ModuleManager.getReceivable(key, opcode);
		if (model == null)
			return false;
		
		this.methodModel = model;
		
		/* 读取网络包 */
		if(!read())
			return false;
		
		/* 将包处理加入到线程池 */
		ThreadPoolManager.getInstance().executeNetwork(this);
		return true;
	}
	
	@Override
	protected void readImpl() 
	{
		objs = new Object[methodModel.getCommandInfoModel().length + 1];
		
		/* 每个控制器第一个参数都未连接 */
		objs[0] = getConnection();
		
		Resolve.resolveReceivable(objs, buffer, methodModel.getCommandInfoModel());
	}

	@Override
	public void runImpl() 
	{
		try 
		{			
			methodModel.execute(methodModel.getObj(), objs);
		} 
		catch (Throwable e) 
		{
			log.error(new StringBuilder().append(getConnection()).append(",控制器:").
					append(methodModel.getObj().getClass().getName()).append("方法：").
					append(methodModel.getMethod().getName()).append("执行出错。").toString(), e);
		}
	}

	@Override
	protected int selecterCode() 
	{
		return conn.getConnID();
	}
	
	

}
